<template>
  <div class="app-container">
    <div class="topSearch">
      <template v-if="type !== 'UNKNOWN'">
        <el-row>
          <el-button
            type="primary"
            @click="showDialog('add')"
          >Authorize New Store</el-button>
          <el-button
            type="primary"
            :disabled="true"
          >Detection Authorized</el-button>
        </el-row>
      </template>
      <el-button
        v-if="type === 'UNKNOWN'"
        type="primary"
        @click="showDialog('add')"
      >Add Unknown Store</el-button>
    </div>

    <el-row v-if="tableData.length" style="margin-top: 10px;" :gutter="20">
      <el-col
        v-for="(item, i) in tableData"
        :key="i"
        :xs="24"
        :sm="12"
        :md="12"
        :lg="8"
        :xl="6"
      >
        <div class="storeItem">
          <div v-if="item.status === 0" class="noTip">
            <p>The store is not authorized</p>
            <el-button
              v-preventReClick
              type="primary"
              @click="authorizationAgain(item.id)"
            >Update Authorized</el-button>
            <el-button
              type="primary"
              @click="deleteItem(item.id)"
            >Delete</el-button>
          </div>
          <p class="storeName">
            <span
              class="name"
            ><svg-icon icon-class="store" />{{ item.name }}</span>
            <el-button
              v-if="item.status === 1 && type !== 'UNKNOWN'"
              @click="goStore(item.name)"
            >Go to store</el-button>
          </p>
          <div class="storeCont">
            <div>
              <p class="nums">0</p>
              <p class="title">Today orders</p>
            </div>
            <div>
              <p class="nums">{{ item.total }}</p>
              <p class="title">Total</p>
            </div>
            <div>
              <p class="nums">{{ item.amount }}</p>
              <p class="title">Amount</p>
            </div>
            <div>
              <p class="nums">{{ item.pending }}</p>
              <p class="title">Pending</p>
            </div>
            <div>
              <p class="nums">{{ item.confirm }}</p>
              <p class="title">Confirm</p>
            </div>
            <div>
              <p class="nums">{{ item.produceing }}</p>
              <p class="title">Produce</p>
            </div>
            <div>
              <p class="nums">{{ item.packing }}</p>
              <p class="title">packing</p>
            </div>
            <div>
              <p class="nums">{{ item.trash }}</p>
              <p class="title">Trash</p>
            </div>
            <div>
              <p class="nums">{{ item.shipped }}</p>
              <p class="title">Shipped</p>
            </div>
          </div>
          <div class="btns">
            <template v-if="type !== 'UNKNOWN'">
              <el-button
                v-preventReClick
                type="primary"
                @click="authorizationAgain(item.id)"
              >Update Authorized</el-button>
              <el-button
                v-preventReClick
                type="primary"
                @click="orderPull(item.id)"
              >Sync orders</el-button>
              <el-button
                type="primary"
                @click="goProduct(item.id)"
              >Product List</el-button>
            </template>
            <el-button
              type="primary"
              @click="goOrder(item.id)"
            >Order List</el-button>
            <el-button
              type="primary"
              @click="deleteItem(item.id)"
            >Delete</el-button>
            <el-button
              type="primary"
              @click="showDialog('edit', item.id)"
            >Edit</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <div v-else class="noDataTip">No store</div>

    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑授权弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="550px"
      @close="closeDialog('ruleForm')"
    >
      <div v-loading="dialogLoading" class="dialogLoadingBox">
        <el-form
          ref="ruleForm"
          :model="dialogForm"
          :rules="rules"
          label-width="120px"
        >
          <template v-if="type === 'SHOPIFY'">
            <el-form-item prop="isHigh" label="version">
              <el-radio v-model="dialogForm.isHigh" :label="1">High version</el-radio>
              <el-radio v-model="dialogForm.isHigh" :label="0">Low version</el-radio>
            </el-form-item>
          </template>

          <el-form-item prop="name" label="store name">
            <el-input
              v-model="dialogForm.name"
              clearable
              placeholder="store name"
            />
          </el-form-item>
          <template v-if="type === 'SHOPIFY' && dialogForm.isHigh===0">
            <el-form-item prop="secretKey" label="secretKey">
              <el-input
                v-model="dialogForm.secretKey"
                clearable
                placeholder="secretKey"
              />
            </el-form-item>
            <el-form-item prop="secretToken" label="secretToken">
              <el-input
                v-model="dialogForm.secretToken"
                clearable
                placeholder="secretToken"
              />
            </el-form-item>
          </template>
          <template v-if="type === 'WOOCOMMERCE'">
            <el-form-item prop="secretKey" label="secret key">
              <el-input
                v-model="dialogForm.secretKey"
                clearable
                placeholder="secret key"
              />
            </el-form-item>
            <el-form-item prop="secretToken" label="secret token">
              <el-input
                v-model="dialogForm.secretToken"
                clearable
                placeholder="secret token"
              />
            </el-form-item>
            <el-form-item prop="url" label="store url">
              <el-input
                v-model="dialogForm.url"
                clearable
                placeholder="store url"
              />
            </el-form-item>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog('ruleForm')">Cancel</el-button>
          <el-button
            v-preventReClick
            type="primary"
            @click="submitData('ruleForm')"
          >Confirm</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  authorizedPage,
  authorizedRead,
  addShopify,
  addWooc,
  addUnknown,
  authorizedAuth,
  authorizedValid,
  editShopify,
  editWooc,
  editUnknown,
  authorizedDelete,
  orderPull
} from '@/api/authorized';
import {
  storeAmountStat,
  storeQuantityStat,
  storeStatusStat
} from '@/api/common';
import { postResult } from '@/utils/dataFormat';
import { downloadUrl } from '@/utils/downLoad';
export default {
  props: {
    type: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      dialogLoading: false,
      dialogType: 'add',
      dialogForm: {},
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        name: [
          {
            validator: this.checkStr,
            required: true,
            trigger: ['blur', 'change']
          }
        ],
        secretKey: [{ validator: this.checkStr, required: true }],
        secretToken: [{ validator: this.checkStr, required: true }],
        url: [{ validator: this.checkStr, required: true }]
      }
    };
  },
  computed: {
    dialogTitle: function() {
      return this.dialogType === 'add'
        ? 'Add'
        : this.dialogType === 'edit'
          ? 'Edit'
          : '';
    },
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loading = true;
      authorizedPage({
        type: this.type,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }).then((res) => {
        this.tableData = res.data.data;
        this.total = res.data.totalCount;
        this.loading = false;
        res.data.data.forEach((item, index) => {
          storeAmountStat(item.id).then((res) => {
            const dataItem = JSON.parse(JSON.stringify(this.tableData[index]));
            dataItem.amount = res.data;
            this.$set(this.tableData, index, dataItem);
          });
          storeQuantityStat(item.id).then((res) => {
            const dataItem = JSON.parse(JSON.stringify(this.tableData[index]));
            dataItem.total = res.data;
            this.$set(this.tableData, index, dataItem);
          });
          storeStatusStat(item.id).then((res) => {
            const dataItem = JSON.parse(JSON.stringify(this.tableData[index]));
            Object.assign(dataItem, {
              ...res.data
            });
            this.$set(this.tableData, index, dataItem);
          });
        });
      });
    },
    showDialog(type, id) {
      this.dialogFormVisible = true;
      this.dialogType = type;
      if (this.type === 'SHOPIFY' && type === 'add') {
        this.$set(this.dialogForm, 'isHigh', 1);
      }
      if (type === 'edit') {
        // 编辑
        this.dialogLoading = true;
        authorizedRead(id).then((res) => {
          this.dialogLoading = false;
          this.dialogForm = res.data;
        });
      }
    },
    submitData(ruleForm) {
      // 添加/编辑授权
      this.$refs[ruleForm].validate(async(valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            if (this.type === 'SHOPIFY') {
              addShopify(this.dialogForm).then((res) => {
                postResult(res, this.$message, this.init);
                if (res.data !== '') {
                  setTimeout(() => {
                    downloadUrl(res.data);
                  }, 1500);
                }
                if (res.code === 200) {
                  this.dialogFormVisible = false;
                }
              });
            } else if (this.type === 'WOOCOMMERCE') {
              addWooc(this.dialogForm).then((res) => {
                postResult(res, this.$message, this.init);
                if (res.code === 200) {
                  this.dialogFormVisible = false;
                }
              });
            } else if (this.type === 'UNKNOWN') {
              addUnknown(this.dialogForm).then((res) => {
                postResult(res, this.$message, this.init);
                if (res.code === 200) {
                  this.dialogFormVisible = false;
                }
              });
            }
          } else if (this.dialogType === 'edit') {
            if (this.type === 'SHOPIFY') {
              const { name, id } = this.dialogForm;
              editShopify({ id, name }).then((res) => {
                postResult(res, this.$message, this.init);
                this.dialogFormVisible = false;
                if (res.code === 200) {
                  this.dialogFormVisible = false;
                }
                if (res.data !== '') {
                  setTimeout(() => {
                    downloadUrl(res.data);
                  }, 1500);
                }
              });
            } else if (this.type === 'WOOCOMMERCE') {
              const { id, name, secretKey, secretToken, url } = this.dialogForm;
              editWooc({ id, name, secretKey, secretToken, url }).then(
                (res) => {
                  postResult(res, this.$message, this.init);
                  if (res.code === 200) {
                    this.dialogFormVisible = false;
                  }
                }
              );
            } else if (this.type === 'UNKNOWN') {
              const { id, name } = this.dialogForm;
              editUnknown({ id, name }).then((res) => {
                postResult(res, this.$message, this.init);
                if (res.code === 200) {
                  this.dialogFormVisible = false;
                }
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    authorizationAgain(id) {
      // 重新授权
      const httpUrl =
        this.type === 'WOOCOMMERCE' ? authorizedValid : authorizedAuth;
      httpUrl(id).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
          if (this.type === 'SHOPIFY') {
            this.$message.success('About to jump to external links');
            setTimeout(() => {
              downloadUrl(res.data);
            }, 1500);
          }
        }
      });
    },
    orderPull(id) {
      // 拉取订单
      orderPull([id]).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
        }
      });
    },
    closeDialog(ruleForm) {
      this.dialogFormVisible = false;
      this.dialogForm = {};
      this.$refs[ruleForm].resetFields();
    },
    deleteItem(id) {
      // 删除
      this.$confirm(
        'This action will permanently delete the authorized. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'cancel',
          type: 'warning'
        }
      )
        .then(() => {
          const ids = [];
          ids.push(id);
          authorizedDelete(ids).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {
          this.$message.info('undeleted');
        });
    },
    goStore(name) {
      if (this.type === 'SHOPIFY') {
        downloadUrl(`https://${name}.myshopify.com/admin`);
      } else {
        downloadUrl(`https://${name}.com/wp-login.php`);
      }
    },
    goOrder(id) {
      this.$router.push({
        name: 'Orders',
        params: {
          storeId: id
        }
      });
    },
    goProduct(id) {
      const name = this.type === 'SHOPIFY' ? 'Shopify' : 'Wooc';
      this.$router.push({
        name,
        params: {
          storeId: id,
          state: '1'
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/variables.scss';
.app-container {
  margin-bottom: 40px;
}
.storeItem {
  position: relative;
  width: 100%;
  height: 100%;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  text-align: center;
  padding: 0 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  .storeName {
    display: flex;
    justify-content: space-between;
    color: $themeColor;
    font-size: 18px;
    padding: 18px 0;
    span {
      white-space: nowrap;
      overflow: hidden;
      margin-right: 10px;
      text-overflow: ellipsis;
      font-weight: 600;
      font-size: 20px;
      .svg-icon {
        margin-right: 10px;
      }
    }
    .el-button {
      font-size: 13px;
      padding: 4px 8px;
      margin-left: 0;
      border-radius: 2px;
    }
  }
  .storeCont {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    font-size: 16px;
    > div {
      width: 31%;
      padding: 0 10px;
      background: #f8f8f8;
      margin-bottom: 10px;
      .title {
        padding-bottom: 10px;
        white-space: nowrap;
        overflow: hidden;
      }
      .nums {
        line-height: 36px;
        color: #333333;
        font-size: 14px;
        font-weight: bold;
      }
    }
  }
  .btns {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 5px 0;
    .el-button {
      font-size: 13px;
      padding: 4px 8px;
      margin-bottom: 10px;
      margin-left: 0;
      margin-right: 10px;
      border-radius: 2px;
    }
  }
  .noTip {
    position: absolute;
    z-index: 2;
    top: 59px;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding-top: 60px;
    p {
      padding-bottom: 30px;
    }
  }
}
.noDataTip {
  text-align: center;
  padding-top: 50px;
  color: #848484;
}
</style>
